import { FormSetProps } from "@/components/Form";
import type { Ref } from "vue";

const TOKEN_KEY = "token"

/**
 * 重置表单
 */
export function resetForm(form: any, defaultValueObj: any, formRef?: Ref) {
  for (const key in form.value) {
    if (key in defaultValueObj) {
      form.value[key] = defaultValueObj[key];
    } else {
      delete form.value[key];
    }
  }

  formRef?.value.resetFields();
}

/**
 * 树结构搜索
 */
export function treeSearch(tree: any[], targetKey: string, targetValue: string | number): any | null {
  if (!tree || tree.length === 0) {
    return null;
  }

  for (const item of tree) {
    if (item[targetKey] === targetValue) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const result = treeSearch(item.children, targetKey, targetValue);
      if (result !== null) {
        return result;
      }
    }
  }

  return null;
}

/**
 * 获取token
 */
export function getToken() {
  return localStorage.getItem(TOKEN_KEY);
}

/**
 * 设置token
 */
export function setToken(token: string) {
  localStorage.setItem(TOKEN_KEY, token);
}

/**
 * 控制表单项显隐
 */
export function setFormItemHidden(setSchema: (schemaProps: FormSetProps[]) => Promise<void>, value: boolean, fields: string[]) {
  setSchema(fields.map(item => ({
    field: item,
    path: "hidden",
    value
  })))
}